package com.definity.toolkit.web.taglib;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import com.definity.security.common.Role;
import com.definity.security.common.User;

public class SecurityTag extends BaseTag {

	private static final long serialVersionUID = -264849425928678551L;

	private String hasRole;
	
	public SecurityTag() {

	}
	
	public String getHasRole() {
		return hasRole;
	}
	
	public void setHasRole(String hasRole) {
		this.hasRole = hasRole;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		User user = (User) request.getSession().getAttribute("dwtuser");
		if (user == null)
			return SKIP_BODY;
		
		if (hasRole == null || hasRole.isEmpty())
			return EVAL_BODY_INCLUDE;
		
		List<String> roleNamesList = new ArrayList<String>();
		
		Set<Role> roles = (Set<Role>) user.getRoles();
		for (Role role : roles) {
			roleNamesList.add(role.getName());
		}
		
		String[] roleNames = hasRole.split(",");
		for (String roleName : roleNames) {
			if (roleNamesList.contains(roleName)) {
				return EVAL_BODY_INCLUDE;
			}
		}
		
		return SKIP_BODY;
	}
	
}
